package com.hspedu.controller;

import com.hspedu.entity.Member;
import com.hspedu.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.security.PublicKey;
import java.util.List;

@RestController
@Slf4j
public class MemberConsumerController {
    /**
     * MEMBER-SERVICE-PROVIDER服务提供方【集群】注册到eureka的别名
     * MEMBER-SERVICE-PROVIDER目前有两个，所以需要负载均衡，增加注解@LoadBalanced赋予RestTemplate负载均衡的能力，默认轮询
     */
    public static final String MEMBER_SERVICE_PROVIDER="http://member-service-provider";
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/discovery")
    public Object getDiscovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("服务名={}",service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                log.info("id={},host={}.port={},uri={}",instance.getServiceId(),
                        instance.getHost(),instance.getPort(),instance.getUri());
            }
        }
        return discoveryClient;
    }
    @PostMapping("/consumer/save")
    public Result save(Member member){
        log.info("member-service-consumer.menber={}",member);
        return restTemplate.postForObject(MEMBER_SERVICE_PROVIDER+"/member/save",
                member,Result.class);
    }
    @GetMapping("/consumer/getMemberById")
    public Result<Member> getByID(@RequestParam("id") Long id){
      return  restTemplate.getForObject(MEMBER_SERVICE_PROVIDER+"/member/getMemberById?id="+id,Result.class);
    }
}
